package com.druid.controller;

import com.druid.model.ResponseData;
import com.druid.request.ChatGptRequest;
import com.druid.request.PicAiRequest;
import com.druid.response.openai.ImageResponse;
import com.druid.service.OpenAIService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


@Controller
@AllArgsConstructor
@Log4j2
@RestController
@RequestMapping("openAi")
public class OpenAIController {

    private final OpenAIService openAIService;

    @PostMapping(value = "chatWithAi", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseData<String> chatWithAi(@RequestBody @Validated ChatGptRequest chatGptRequest) {

        return ResponseData.SUCCESS(
                openAIService.generateChatText(chatGptRequest.getPrompts(),chatGptRequest.getUserId())
        );
    }

    @PostMapping("picWithAi")
    public ResponseData<?> picWithAi(@ModelAttribute PicAiRequest picAiRequest) throws IOException {

        ImageResponse imageResponse = openAIService.generateImage(picAiRequest);
        if ( imageResponse == null || CollectionUtils.isEmpty(imageResponse.getData()) ) {
            return ResponseData.FAILURE("系统错误，为获取到生成图片联机");
        }

        List<String> urlList = imageResponse.getData().stream().map(ImageResponse.ImageResponseData::getUrl).collect(Collectors.toList());
        return ResponseData.SUCCESS(urlList);

    }
}

